package com.luyuan.crm.member.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.service.MemberService;
import com.luyuan.crm.member.service.OnlineMemberService;
import com.ruijie.components.security.model.AppUser;

public class AopLogout implements ApplicationListener {
    private static final Log logger = LogFactory.getLog(AopLogin.class);

    private OnlineMemberService onlineService;

    private MemberService memberService;

    public void setOnlineService(OnlineMemberService onlineService) {
        this.onlineService = onlineService;
    }

    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof HttpSessionDestroyedEvent) {
            HttpSessionDestroyedEvent authEvent = (HttpSessionDestroyedEvent) event;
            SecurityContext securityContext = (SecurityContext) authEvent.getSession().getAttribute(
                    "SPRING_SECURITY_CONTEXT");
            if (securityContext == null) {
                return;
            }
            AppUser appUser = (AppUser) securityContext.getAuthentication().getPrincipal();
            if (appUser != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("模拟输出用户登录日志:[" + java.util.Calendar.getInstance().getTime() + "] "
                            + appUser.getUsername());
                }
                Member member = memberService.getByAccount(appUser);
                if (member != null) {
                    onlineService.offlineMember(member);
                }
            }
        }
    }

}